

/**
 *\*\file log.c
 *\*\author Nations
 *\*\version v1.0.0
 *\*\copyright Copyright (c) 2019, Nations Technologies Inc. All rights reserved.
 **/
#include "bsp_4g_task.h"
#include "bsp_4g_common.h"

uart_4G_para *device_4g = RT_NULL;
uart_4G_para device_4g_para;

rec_4G_unit rec_send_cache;
char msg_package[512];

#define FAKE_PUB_MSG_ENABLE 0
#define FAKE_PUB_TOPIC "fake_keepalive_msg"
#define FAKE_PUB_MSG "fake keepalive msg"

#if PRINT_DEBUG
#define PRINTF(fmt, ...) printf(fmt, ##__VA_ARGS__)
#else
#define PRINTF(fmt, ...)
#endif

/**
 * @brief
 *
 * @param para
 * @return int
 */
int driver_4Gmoudle_init(driver_4g_para_t *para)
{

    device_4g = &device_4g_para;
    if (device_4g == NULL)
        return -1;
    memset((void *)device_4g, 0, sizeof(uart_4G_para));

    device_4g->read_buffer_size = para->rec_cache_length;
    device_4g->send_buffer_size = para->send_cache_length;

    rec_send_cache.buf = msg_package;
    rec_send_cache.status = DRV_4G_REC_IDLE;
    device_4g->current_read = &rec_send_cache;
    device_4g->current_write = &rec_send_cache;
    Gpio_4g_Init();  // IO初始化
    usart_4g_init(); // 串口初始化

    return 0;
}

/** URC侦听队列，推出
 * @brief
 *
 * @return int
 */
int mqtt_recive_urc_list_pop(void)
{
    unsigned char current_rec = 0;
    //    for (int i = 0; i < MQTT_URC_LIST_SIZE; i++)
    //    {
    //        current_rec = (device_4g->mqttrecive.last_recive + i) % MQTT_URC_LIST_SIZE;
    //        if (device_4g->mqttrecive.mark[current_rec] == 1)
    //        {
    //            device_4g->mqttrecive.mark[current_rec] = 0;
    //            device_4g->mqttrecive.last_recive = current_rec;
    //            return current_rec;
    //        }
    //    }
    return -1;
}

/** 4g模组驱动主任务
 * @brief
 *
 * @param para
 */
int Device_4G_Task(unsigned short para)
{
	return -1;
#define CHECK_RETRY_TIME_OUT(times)       \
    if (device_4g->retytimes >= times)    \
    {                                     \
        device_init_step = DEVCIE_REBOOT; \
    }

#define SET_TO_NEXT_STEP(X)       \
    {                             \
        device_init_step = X;     \
        device_4g->retytimes = 0; \
    }

    device_4g->factory_data_send = 2;
    device_4g->battery = para;
    _device_init_step_enum device_init_step = DEVCIE_REBOOT;
    int relength = 0, datasendlength = 0, result, resta, msgid;
    unsigned int send_error_time_out = 0, rec_error_time_out = 0, randtime = 0;
    char *location, *str_end, *data_location;

    rec_4G_unit *rec = NULL;
    _server_connct_step_enum http_step;
    // int model_reboot_cnt = 0;
    while (1)
    {
        switch (device_init_step)
        {
        case DEVCIE_REBOOT:
            // model_reboot_cnt++;

            device_4g->CSQ_RSSI = 99;
            device_4g->link_sta = 0;
            device_4g->sim_sta = 0;
            device_4g->net_sta = 0;
            device_4g->send_busy = 0;
            device_4g->retytimes = 0;
            device_4g->connecting_sta = 0;
            device_init_step = DEVICE_AT_TEST;

            PRINTF("device_reboot\n");
#if 1
            EC_Device_Power_High();
            EC_Device_Reset_High();
            rt_thread_mdelay(100);
            EC_Device_Reset_Low();
            EC_Device_Power_Low();
            rt_thread_mdelay(4000); // 关机
            EC_Device_Reset_High();
            EC_Device_Power_High();
            rt_thread_mdelay(500); // 延迟1秒模组复位
            EC_Device_Reset_Low();
#endif
            PRINTF("reboot end\n");
            srand(GetTick());
            break;
        case DEVICE_AT_TEST:
            rec = SEND_CMD("AT\r\n", 1000);
            if (rec)
            {
                DATA_TRIM(rec);
                if (RT_NULL != rt_strstr(rec->buf, RE_OK))
                {
                    PRINTF("ATtestok\n");
                    SET_TO_NEXT_STEP(DEVICE_COM_ECHO_OFF);
                }
            }
            CHECK_RETRY_TIME_OUT(5);
            break;
        case DEVICE_COM_ECHO_OFF:
            rec = SEND_CMD("ATE0\r\n", 1000);
            if (rec)
            {
                DATA_TRIM(rec);
                if (RT_NULL != rt_strstr(rec->buf, RE_OK))
                {
                    PRINTF("AT echo off\n");
                    SET_TO_NEXT_STEP(DEVICE_SET_TOKEN);
                }
            }
            CHECK_RETRY_TIME_OUT(5);
            break;
        case DEVICE_SET_TOKEN:
        {
            rec = SEND_CMD("AT+QLBSCFG=\"token\",\"9kgK1CT6A3t85921\"\r\n", 1000);
            if (rec)
            {
                DATA_TRIM(rec);
                if (RT_NULL != rt_strstr(rec->buf, RE_OK))
                {
                    PRINTF("AT token\n");
                    SET_TO_NEXT_STEP(DEVICE_GET_IMEI);
                }
            }
            CHECK_RETRY_TIME_OUT(5);
            break;
        }
        case DEVICE_GET_IMEI:
            rec = SEND_CMD("AT+GSN\r\n", 1000);
            if (rec)
            {
                DATA_TRIM(rec);
                if (RT_NULL != rt_strstr(rec->buf, RE_OK))
                {
                    PRINTF("AT IMEI:%s\n", rec->buf);
                    memset((void *)device_4g->moudle.imei, 0, sizeof(device_4g->moudle.imei));
                    if (1 == sscanf((char *)rec->buf, "%*[^\n]\n%s\r\n", device_4g->moudle.imei))
                        SET_TO_NEXT_STEP(DEVICE_GET_QCCID);
                }
            }
            rt_thread_mdelay(500);
            CHECK_RETRY_TIME_OUT(5);
            break;
        case DEVICE_GET_QCCID:
            rec = SEND_CMD("AT+QCCID\r\n", 1000);
            if (rec)
            {
                DATA_TRIM(rec);
                if (RT_NULL != rt_strstr(rec->buf, RE_OK))
                {
                    PRINTF("AT qccid:%s\n", rec->buf);
                    memset((void *)device_4g->moudle.qccid, 0, sizeof(device_4g->moudle.qccid));
                    if (1 == sscanf((char *)rec->buf, "%*[^+]+QCCID: %s\r\n", device_4g->moudle.qccid))
                        SET_TO_NEXT_STEP(DEVCIE_CHECK_SIM);
                }
            }
            rt_thread_mdelay(500);
            CHECK_RETRY_TIME_OUT(5);
            break;
        // case DEVICE_GET_CVERSION:
        //     break;
        // case DEVICE_GET_QGMR:
        //     break;
        // case DEVICE_GET_CGMR:
        //     break;
        case DEVCIE_CHECK_SIM: // SIM卡状态检测
            rec = SEND_CMD("AT+CPIN?\r\n", 2000);
            if (rec)
            {
                DATA_TRIM(rec);
                PRINTF("AT sim:%s\n", rec->buf);
                if (RT_NULL != rt_strstr(rec->buf, RE_OK))
                {
                    if (RT_NULL != rt_strstr(rec->buf, SIM_OK))
                    {
                        SET_TO_NEXT_STEP(DEVICE_GET_CSQ);
                        device_4g->sim_sta = 1;
                        PRINTF("sim ok\n");
                    }
                }
            }
            rt_thread_mdelay(500); // 延迟检测，防止SIM卡检测失败反复重启模组
            CHECK_RETRY_TIME_OUT(10);
            break;
        case DEVICE_GET_CSQ:
            rec = SEND_CMD("AT+CSQ\r\n", 1000);
            if (rec)
            {
                DATA_TRIM(rec);
                if (RT_NULL != rt_strstr(rec->buf, RE_OK))
                {
                    PRINTF("AT CSQ:%s\n", rec->buf);
                    device_4g->CSQ_RSSI = 99;
                    if (sscanf(rec->buf, (char const *)"\r\n+CSQ: %d[^.]", &(device_4g->CSQ_RSSI)) == 1)
                    {
                        if (device_4g->CSQ_RSSI != 99)
                            SET_TO_NEXT_STEP(DEVICE_NET_CREG);
                    }
                }
            }
            rt_thread_mdelay(500);
            CHECK_RETRY_TIME_OUT(10);
            break;
        case DEVICE_NET_CREG:
            rec = SEND_CMD("AT+CREG=1\r\n", 1000);
            if (rec)
            {
                DATA_TRIM(rec);
                if (RT_NULL != rt_strstr(rec->buf, RE_OK))
                {
                    PRINTF("AT CREG:%s\n", rec->buf);
                    SET_TO_NEXT_STEP(DEVICE_CLOSE_DATA_ECH0);
                }
            }
            rt_thread_mdelay(500);
            CHECK_RETRY_TIME_OUT(2);
            break;
        case DEVICE_CLOSE_DATA_ECH0:
            rec = SEND_CMD("AT+QISDE=0\r\n", 1000);
            if (rec)
            {
                DATA_TRIM(rec);
                if (RT_NULL != rt_strstr(rec->buf, RE_OK))
                {
                    PRINTF("AT data ech0:%s\n", rec->buf);
                    SET_TO_NEXT_STEP(DEVCIE_GET_NET_STATE);
                }
            }
            rt_thread_mdelay(500);
            CHECK_RETRY_TIME_OUT(2);
            break;
        case DEVCIE_GET_NET_STATE:
            rec = SEND_CMD("AT+CREG?\r\n", 1000);
            device_4g->connecting_sta = 1;
            if (rec)
            {
                DATA_TRIM(rec);
                PRINTF("AT net sta:%s\n", rec->buf);
                if (RT_NULL != rt_strstr(rec->buf, NET_ON) ||
                    RT_NULL != rt_strstr(rec->buf, NET_ONx))
                {
                    SET_TO_NEXT_STEP(DEVCIE_GET_LOCATION);
                    device_4g->net_sta = 1; // 驻网成功
                    device_4g->connecting_sta = 0;
                }
            }
            CHECK_RETRY_TIME_OUT(600); // 1分钟内驻网
            break;
        case DEVCIE_GET_LOCATION:
        {
            rec = SEND_CMD("AT+QLBS\r\n", 1000);
            if (rec)
            {
                DATA_TRIM(rec);
                PRINTF("AT QLBS:%s\n", rec->buf);
                if (sscanf(rec->buf, (char const *)"\r\n+QLBS: 0,%f,%f",
                           &(device_4g->location.longitude),
                           &(device_4g->location.latitude)) == 2)
                {
                    SET_TO_NEXT_STEP(DEVICE_CFG_TCP_KEEPALIVE);
                }
            }
            CHECK_RETRY_TIME_OUT(600); // 1分钟内驻网
            break;
        }
        case DEVICE_CFG_TCP_KEEPALIVE: // 开启keepalive
            rec = SEND_CMD("AT+QICFG=\"tcp/keepalive\",1,10,25,3\r\n", 1000);
            if (rec)
            {
                DATA_TRIM(rec);
                if (RT_NULL != rt_strstr(rec->buf, RE_OK))
                {
                    PRINTF("AT kpalive:%s\n", rec->buf);
                    SET_TO_NEXT_STEP(DEVICE_ENABLE_URC);
                }
            }
            CHECK_RETRY_TIME_OUT(3);
            break;
        case DEVICE_ENABLE_URC: // 不使用缓存
            rec = SEND_CMD("AT+QCFG=\"urc/cache\",0\r\n", 1000);
            if (rec)
            {
                DATA_TRIM(rec);
                if (RT_NULL != rt_strstr(rec->buf, RE_OK))
                {
                    PRINTF("AT urc:%s\n", rec->buf);
                    SET_TO_NEXT_STEP(DEVICE_HTTP_CONNECT);
                }
            }
            CHECK_RETRY_TIME_OUT(3);
            break;

        case DEVICE_HTTP_CONNECT:
            //device_4g->mqtt_link_sta = 0;
            http_step = server_connect();
            PRINTF("server_connect return %d\n", http_step);
            //            if (device_4g->cache == RT_NULL) // 生产测试任务
            //            {
            //                device_4g->write_length = 0;
            //                device_4g->factory_data_send = 0;
            //                devcie_data_rec_reset();
            //                PRINTF("step to DEVICE_TASK_FACTORY_STOP\n");
            //                SET_TO_NEXT_STEP(DEVICE_TASK_FACTORY_STOP);
            //                break;
            //            }
            //            else
            SET_TO_NEXT_STEP(DEVICE_HTTP_DISCONNECT);
            CHECK_RETRY_TIME_OUT(3);
            // SET_TO_NEXT_STEP(DEVCIE_REBOOT); // 无需等待，直接重启模组
            break;
#if 0
        case DEVICE_MQTT_CONNECT:
            device_4g->mqtt_restart_connect = 1; // 标记主任务循环首次连接
            mqtt_step = mqtt_service();
            PRINTF("mqtt_connct return %d\n", mqtt_step);
            if (mqtt_step == MQTT_CONNECT_SUCCESS)
            {
//                user_uart_reinit(device_4g->DTU_para.uart_baud,
//                                 device_4g->DTU_para.uart_databit,
//                                 device_4g->DTU_para.uart_stopbit,
//                                 device_4g->DTU_para.uart_parity);
                SET_TO_NEXT_STEP(DEVCIE_NET_DATA_LISTEN);
                device_4g->mqtt_link_sta = 1;
                device_4g->mqttrecive.status = MQTT_DATA_REC_IDLE;
                device_4g->mqttsend.status = MQTT_DATA_TRANS_IDLE;
                device_4g->last_transmission_tick = rt_tick_get();
                device_4g->last_pub_msg_tick = rt_tick_get();
                device_4g->keepalive_pub_flag = 0;
                relength = 0;
                device_4g->mqttrecive.last_recive = 0;
                memset((void *)device_4g->mqttrecive.mark, 0, MQTT_URC_LIST_SIZE);
                device_4g->mqttsend.msgid = 1;
                devcie_data_rec_reset();
                break;
            }
            // else
            //     CHECK_RETRY_TIME_OUT(3);
            SET_TO_NEXT_STEP(DEVCIE_REBOOT); // 无需等待，直接重启模组
            break;
        case DEVCIE_NET_DATA_LISTEN:
            // 数据接收监测
            if (relength != device_data_rec_length()) // 数据未接收完全
            {
                relength = device_data_rec_length();
            }
            else if (relength != 0) // 数据接收完全
            {
                // 切换接收缓存
                rec->buf = device_4g->current_rec->buf;
                if (device_4g->current_rec->next->status == DRV_4G_REC_IDLE)
                {
                    device_4g->current_rec = device_4g->current_rec->next;
                }
                // 复位接收
                device_data_rec_restart();
                rec->buf[relength] = 0;
                str_end = &rec->buf[relength];
                PRINTF("listen :\n%d\n", relength);
                if (rt_strstr(rec->buf, "\r\nERROR\r\n")) // 出现报错，直接发起重连
                {
                    SET_TO_NEXT_STEP(DEVICE_HTTP_CONNECT); // 重新请求参数重新连接
                    PRINTF("error %d\n", __LINE__);
                    rt_thread_mdelay(500); // 延迟500ms
                    break;
                }
                // location = rt_strstr(rec->buf, "+QMTSTAT: 0,");
                location = rt_strstr(rec->buf, "+QMTSTAT:");
                if (location) // 错误上报
                {
                    SET_TO_NEXT_STEP(DEVICE_HTTP_CONNECT); // 重新请求参数重新连接
                    PRINTF("QMTSTAT\n %s\n", rec->buf);
                    rt_thread_mdelay(500); // 延迟500ms
                    break;
                }
                location = rt_strstr(rec->buf, "+QMTRECV");
                if (location) // 数据接收
                {
                    device_4g->last_transmission_tick = rt_tick_get();
                    while (location < str_end)
                    {
                        if (device_4g->mqttrecive.status == MQTT_DATA_REC_DATA_IN &&
                            1 == sscanf(location, "+QMTRECV: %*[^,],%*[^,],%*[^,],%d,", &result))
                        {
                            // 找数据
                            data_location = location;
                            for (int i = 0; i < 4; i++)
                            {
                                data_location = rt_strstr((char *)data_location, ",");
                                if (data_location)
                                {
                                    data_location += 1;
                                }
                                else
                                {
                                    data_location = 0; // 找不到数据
                                    break;
                                }
                            }
                            if (data_location)
                            {
                                data_location++;                           // 去掉左侧引号
                                relength = (int)(str_end - data_location); // 当前报文剩余长度
                                if (relength >= result)                    // 接收长度大于payload（后边有粘包）按照payload接收
                                {
                                    relength = result;
                                }
                                else if (result > MQTT_MAX_REC_FRAME) // 接收超过帧长，直接截断
                                {
                                    relength = MQTT_MAX_REC_FRAME;
                                }
//                                resta = user_uart_send(data_location, relength); // 启动数据发送
                                device_4g->mqtt_data_sta = 1;
                                location = data_location + relength;

                                if (resta < 0)
                                {
                                    device_4g->mqttrecive.status = MQTT_DATA_REC_IDLE;
                                    rec_error_time_out = 0;
                                    PRINTF("data to user err\n");
                                }
                                else
                                {
                                    PRINTF("data to user\n");
                                    device_4g->mqttrecive.status = MQTT_DATA_REC_IDLE;
                                    rec_error_time_out = 0;
                                }
                            }
                            else
                            {
                                location += sizeof("+QMTRECV: 0,0,0,0,");
                            }
                        }
                        else if (1 == sscanf(location, "+QMTRECV: 0,%d\r\n", &result)) // 此代码必须在后，否侧会报错
                        {
                            PRINTF("mqt rec urc %d\n", result);
                            device_4g->mqttrecive.mark[result] = 1;
                            location += sizeof("+QMTRECV: 0,0\r\n");
                        }
                        // 数据结束
                        if (location >= str_end)
                            break;
                        // 找数据
                        location = rt_strstr(location, "+QMTRECV");
                        if (location == 0)
                            break;
                    }
                }
                // 发送过程控制
                switch (device_4g->mqttsend.status)
                {
                case MQTT_DATA_TRANS_SET:
                    if (rt_strstr(rec->buf, "\r\n>"))
                    {
                        int datasendlength = 0;
                        PRINTF("datasend\n");
                        // 开始发送数据
                        if (!device_4g->keepalive_pub_flag)
                        {
                            // 从数据节点取出数据
                            device_4g->mqttsend.current_chain_node = Chain_func.pop_chain_node(device_4g->cache, NULL);
                            datasendlength = Chain_func.recive_data_from_chain_node(device_4g->mqttsend.current_chain_node,
                                                                                    (unsigned char *)device_4g->Write, device_4g->send_buffer_size);
                        }
                        else
                        {
                            datasendlength = sizeof(FAKE_PUB_MSG) - 1;
                        }
                        if (datasendlength)
                        {
                            if (0 <= driver_4G_data_send(device_4g->Write, datasendlength))
                            {
                                device_4g->mqttsend.status = MQTT_DATA_TRANS_SEND;
                                send_error_time_out = 0;
                            }
                        }
                    }
                    break;
                case MQTT_DATA_TRANS_SEND:
                    location = rt_strstr(rec->buf, "+QMTPUBEX");
                    if (location != RT_NULL)
                    {
                        PRINTF("%s", location);
                        resta = sscanf(location, "+QMTPUBEX: 0,%d,%d\r\n", &msgid, &result);
                        PRINTF("send sta loc:%d id:%d re:%d\n", resta, msgid, result);
                        if (!device_4g->keepalive_pub_flag)
                        {
                            Chain_func.free_chain_node(device_4g->cache, device_4g->mqttsend.current_chain_node);
                        }
                        else
                        {
                            device_4g->keepalive_pub_flag = 0;
                        }
                        if (2 == resta && result == 0) // 发送成功
                        {
                            device_4g->mqttsend.current_chain_node = RT_NULL;
                            device_4g->mqttsend.status = MQTT_DATA_TRANS_IDLE;
                            device_4g->last_transmission_tick = rt_tick_get();
                            device_4g->last_pub_msg_tick = rt_tick_get();
                            device_4g->mqtt_data_sta = 1;
                        }
                        else // 发送失败，重启模组
                        {
                            device_4g->mqttsend.status = MQTT_DATA_TRANS_ERROR;
                            SET_TO_NEXT_STEP(DEVICE_HTTP_CONNECT); // 重新请求参数重新连接
                            PRINTF("error %d\n", __LINE__);
                        }
                    }
                    break;
                default:
                    break;
                }
                relength = 0;
            }

            // 发送保护机制,5秒未出现发送标记，直接重连
            if (device_4g->mqttsend.status == MQTT_DATA_TRANS_SET ||
                device_4g->mqttsend.status == MQTT_DATA_TRANS_SEND)
            {
                send_error_time_out++;
                if (send_error_time_out == 500)
                {
                    send_error_time_out = 0;
                    device_4g->mqttsend.status = MQTT_DATA_TRANS_ERROR;
                    SET_TO_NEXT_STEP(DEVICE_HTTP_CONNECT); // 重新请求参数重新连接
                    PRINTF("error %d\n", __LINE__);
                    break;
                }
            }
            // 数据接受保护机制
            if (device_4g->mqttrecive.status == MQTT_DATA_REC_DATA_IN)
            {
                rec_error_time_out++;
                if (rec_error_time_out == 200) // 发送命令两秒未收到数据，重连
                {
                    SET_TO_NEXT_STEP(DEVICE_HTTP_CONNECT); // 重新请求参数重新连接
                    PRINTF("error %d\n", __LINE__);
                }
            }

            // 接收数据检测，数据接收理应在串口空时进行，4g串口正在处理数据，此时不宜发送
            if (device_4g->send_busy)
            {
                device_4g->send_busy--;
                break;
            }

//            // 检测数据是否可以下发
//            if (!user_uart_send_is_busy() && device_4g->mqttrecive.status == MQTT_DATA_REC_IDLE)
//            {
//                result = mqtt_recive_urc_list_pop();
//                if (result >= 0) // 有数据待接收，发送数据接收命令
//                {
                //    datasendlength = rt_snPRINTF(device_4g->Write, device_4g->read_buffer_size, "AT+QMTRECV=0,%d\r\n", result);

//                    if (0 <= driver_4G_data_send(device_4g->Write, datasendlength))
//                    {
//                        device_4g->mqttrecive.status = MQTT_DATA_REC_DATA_IN;
//                    }
//                    break; // 4g串口占线，进入下一次循环
//                }
//            }

            // 数据发送中,不应处理以下信息
            if (device_4g->mqttsend.status != MQTT_DATA_TRANS_IDLE)
                break;
            // 此处加时间限制
            tick = rt_tick_get();                                                   // 获取系统时间
            if (tick - device_4g->last_transmission_tick > RT_TICK_PER_SECOND * 30) // 10s
            {
                rec = SEND_CMD("AT+QMTCONN?\r\n", 1000);
                if (rec)
                {
                    DATA_TRIM(rec);
                    if (RT_NULL == rt_strstr(rec->buf, "+QMTCONN: 0,3"))
                    {
                        PRINTF("AT+QMTCONN=0?:%s\n", rec->buf);
                        SET_TO_NEXT_STEP(DEVICE_MQTT_CONNECT);
                    }
                    else
                    {
                        device_4g->last_transmission_tick = tick;
                        device_4g->retytimes = 0;
                    }
                }
                CHECK_RETRY_TIME_OUT(3);
            }
#if FAKE_PUB_MSG_ENABLE
            if ((tick - device_4g->last_pub_msg_tick > (device_4g->DTU_para.mqtt_keepalive - 20) * RT_TICK_PER_SECOND) && !device_4g->keepalive_pub_flag) // 10s
            {
                device_4g->keepalive_pub_flag = 1;
            }
#endif

            if (tick > device_4g->old_tick) // 非越界状态
            {
//                if ((tick - device_4g->old_tick) < device_4g->DTU_para.dataperiod) // 判定时间
//                    break;
//                else
//                    device_4g->old_tick = tick; // 更新时间
            }
            else if (tick < device_4g->old_tick) // 越界位置直接启动发送即可
            {
                device_4g->old_tick = tick;
            }

            // 检测队列是否有数据
            device_4g->mqttsend.current_chain_node = Chain_func.peek_chain_node(device_4g->cache, RT_NULL);
            if (device_4g->mqttsend.current_chain_node != NULL)
            {
                datasendlength = Chain_func.get_chain_node_length(device_4g->mqttsend.current_chain_node);
                if (datasendlength <= 0)
                {
                    while (1)
                    {
                        PRINTF("4G_TASGK REC_ERR\r\n");
                    }
                }
                // 启动MQTTpub
                PRINTF("datasendlength %d\n", datasendlength);

//                if (device_4g->DTU_para.mqtt_pubqos)
//                {
//                    if (device_4g->mqttsend.msgid < 65535)
//                        device_4g->mqttsend.msgid++;
//                    else
//                        device_4g->mqttsend.msgid = 1;
//                }
//                else
//                {
//                    device_4g->mqttsend.msgid = 0;
//                }

            //    datasendlength = rt_snPRINTF(device_4g->Write, device_4g->read_buffer_size, "AT+QMTPUBEX=0,%d,%d,0,\"%s\",%d\r\n",
//                                             device_4g->mqttsend.msgid,
//                                             device_4g->DTU_para.mqtt_pubqos,
//                                             device_4g->DTU_para.mqtt_topic_publish, datasendlength);
                if (0 <= driver_4G_data_send(device_4g->Write, datasendlength))
                {
                    device_4g->mqttsend.status = MQTT_DATA_TRANS_SET;
                    send_error_time_out = 0;
                }
            }
            else if (device_4g->keepalive_pub_flag)
            {
//                if (device_4g->DTU_para.mqtt_pubqos)
//                {
//                    if (device_4g->mqttsend.msgid < 65535)
//                        device_4g->mqttsend.msgid++;
//                    else
//                        device_4g->mqttsend.msgid = 1;
//                }
//                else
                {
                    device_4g->mqttsend.msgid = 0;
                }

            //    datasendlength = rt_snPRINTF(device_4g->Write, device_4g->read_buffer_size, "AT+QMTPUBEX=0,%d,%d,0,\"%s\",%d\r\n",
//                                             device_4g->mqttsend.msgid,
//                                             device_4g->DTU_para.mqtt_pubqos,
//                                             FAKE_PUB_TOPIC, sizeof(FAKE_PUB_MSG) - 1);
                if (0 <= driver_4G_data_send(device_4g->Write, datasendlength))
                {
                    device_4g->mqttsend.status = MQTT_DATA_TRANS_SET;
                    send_error_time_out = 0;
                }
            }
            break;
        case DEVICE_TASK_FACTORY_STOP: // 生产测试任务
            if (device_4g->write_length > 0)
            {
                PRINTF("4g_fac_send \n");
                driver_4G_data_send(device_4g->Write, device_4g->write_length);
                device_4g->write_length = 0;
                rt_thread_mdelay(50);
            }
            // 数据接收监测
            if (relength != device_data_rec_length()) // 数据未接收完全
            {
                relength = device_data_rec_length();
            }
            else if (relength != 0) // 数据接收完全
            {
                // 切换接收缓存
                rec->buf = device_4g->current_rec->buf;

                if (device_4g->current_rec->next == DRV_4G_REC_IDLE)
                {
                    device_4g->current_rec = device_4g->current_rec;
                }
                if (device_4g->factory_data_send)
                {
                   // user_uart_send(rec->buf, relength);
                }
                // 复位接收
                device_data_rec_restart();
            }

            break;
#endif
        case DEVICE_TASK_STOP:
            // 时间范围控制在10分钟到30分钟
            randtime = rand();
            if (randtime > 1800000)
                randtime = randtime % 1800000;
            if (randtime < 600000)
                randtime += 600000;
            // 开始延时
            rt_thread_mdelay(randtime);
            SET_TO_NEXT_STEP(DEVCIE_REBOOT); // 重新请求参数重新连接
            break;

        default:
            break;
        }
        rt_thread_mdelay(10);
        if (device_init_step == DEVICE_HTTP_DISCONNECT)
        {
            if (http_step == HTTP_PRAR_READ_SUCCESS)
                return 0;
            else
            {
                return -1;
            }
        }
    }
    return 1;
#undef CHECK_RETRY_TIME_OUT
#undef SET_TO_NEXT_STEP
}

/**
 * @brief
 *
 * @return int
 */
int driver_4Gmoudle_netsta(void)
{
    if (device_4g == RT_NULL)
        return -1;
    return device_4g->net_sta ? 1 : 0;
}
/**
 * @brief
 *
 * @return int
 */
int driver_4Gmoudle_simsta(void)
{
    if (device_4g == RT_NULL)
        return -1;
    return device_4g->sim_sta ? 1 : 0;
}
/**
 * @brief
 *
 * @return int
 */
int driver_4Gmoudle_linksta(void)
{
    if (device_4g == RT_NULL)
        return -1;
    return device_4g->link_sta ? 1 : 0;
}

/**
 * @brief
 *
 * @return int
 */
int driver_4Gmoudle_datalinksta(void)
{
    if (device_4g == RT_NULL)
        return -1;
    //return device_4g->mqtt_link_sta ? 1 : 0;
	return 0;
}
/**
 * @brief
 *
 * @return int
 */
int driver_4Gmoudle_data_trans_sta(void)
{
    if (device_4g == RT_NULL)
        return -1;
    int sta = device_4g->mqtt_data_sta ? 1 : 0;
    device_4g->mqtt_data_sta = 0;
    return sta;
}
/**
 * @brief
 *
 * @return int
 */
int driver_4Gmoudle_RSSI(void)
{
    if (device_4g == RT_NULL)
        return -1;
    int rssi = device_4g->CSQ_RSSI;
    return rssi;
}

/**
 * @brief 开启厂测模式
 *
 * @param sta
 * @return int
 */
int driver_4Gmoudle_factory_set(int sta)
{
    if (device_4g == RT_NULL)
        return -1;
    if (device_4g->factory_data_send == 2)
        return -2;

    if (sta > 0)
        device_4g->factory_data_send = 1;
    else
        device_4g->factory_data_send = 0;
    return 0;
}

/**
 * @brief 直接发送数据到4G模组
 *
 * @param buf
 * @param length
 * @return int
 */
int driver_4Gmoudle_factory_data_send(char *buf, int length)
{
    if (device_4g == RT_NULL)
        return -1;
    if (device_4g->factory_data_send != 1)
        return -2;
    //    rt_memcpy(device_4g->Write, buf, length);
    //    device_4g->write_length = length;
    return 0;
}

int driver_4Gmoudle_net_connecting(void)
{
    if (device_4g == RT_NULL)
        return -1;
    return device_4g->connecting_sta ? 1 : 0;
}